package com.quan.cms.rpc.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.quan.base.common.base.service.support.BaseService;
import com.quan.base.common.exception.BizException;
import com.quan.cms.rpc.api.CmsChannelService;
import com.quan.cms.rpc.dao.mapper.CmsChannelMapper;
import com.quan.cms.rpc.model.CmsChannel;

@Service
public class CmsChannelServiceImpl extends BaseService<CmsChannel, Integer> implements CmsChannelService {
	
	@Autowired
	private CmsChannelMapper mapper ;
	
	@Override
	public int delete(Integer id) throws BizException {
		return recursiveDelete(id);
	}
	
	private int recursiveDelete(Integer id) {
		List<CmsChannel> loadChildrenNode = this.selectChildren(id) ;
		if(null != loadChildrenNode) {
			for (CmsChannel channel : loadChildrenNode) {
				recursiveDelete(channel.getId());
			}
		}
		return super.delete(id) ;
	}

	@Override
	public List<CmsChannel> selectRoot() {
		return this.mapper.selectRoot();
	}

	@Override
	public List<CmsChannel> selectChildren(Integer pid) {
		return this.mapper.selectChildren(pid);
	}

	@Override
	public List<CmsChannel> tree(CmsChannel entity) {
		List<CmsChannel> list = new ArrayList<CmsChannel>() ;
		
		List<CmsChannel> selectRoot = this.selectRoot() ;
		for (CmsChannel channel : selectRoot) {
			list.add(recursive(channel)) ;
		}
		return list;
	}
	
	private CmsChannel recursive(CmsChannel menu) {
		List<CmsChannel> selectChildren = this.selectChildren(menu.getId()) ;
		if(null != selectChildren && !selectChildren.isEmpty()) {
			List<CmsChannel> children = new ArrayList<CmsChannel>() ;
			
			for (CmsChannel childChannel : selectChildren) {
				children.add(recursive(childChannel)) ;
			}
			
			menu.setChildren(children);
		}
		return menu ;
	}

	@Override
	public List<Integer> getParents(Integer id) {
		List<Integer> pidList = new ArrayList<Integer>() ;
		
		CmsChannel channel = super.selectById(id) ;
		if(null != channel) {
			if(null != channel.getPid() && channel.getPid() > 0) {
				getParent(pidList, channel) ;
			} else {
				//pidList.add(channel.getId()) ;
			}
		}
		return pidList;
	}
	
	private void getParent(List<Integer> pidList, CmsChannel channel) {
		pidList.add(channel.getId()) ;
		
		if(null != channel) {
			if(null != channel.getPid() && channel.getPid() > 0) {
				CmsChannel channelParent = super.selectById(channel.getPid()) ;
				getParent(pidList, channelParent) ;
			}
		}
	}

}
